document.addEventListener('DOMContentLoaded', () => {
  const detailContainer = document.getElementById('detail-container');
  const loadingElement = document.getElementById('loading');
  const errorElement = document.getElementById('error');
  
  // 从URL获取ID参数
  const urlParams = new URLSearchParams(window.location.search);
  const id = urlParams.get('id');
  
  if (!id) {
      hideLoading();
      showError('未提供ID参数');
      return;
  }
  
  // 加载详情数据
  fetchDetailData(id);
  
  async function fetchDetailData(itemId) {
      try {
          showLoading();
          
          const response = await fetch(`/api/data/${itemId}`);
          const result = await response.json();
          
          if (!result.success) {
              throw new Error(result.message || '加载数据失败');
          }
          
          renderDetailData(result.data);
          hideLoading();
          showDetailContainer();
      } catch (error) {
          console.error('获取详情数据失败:', error);
          hideLoading();
          showError(error.message || '获取详情数据失败，请稍后再试');
      }
  }
  
  function renderDetailData(data) {
      if (!data) {
          showError('未找到相关数据');
          return;
      }
      
      // 创建详情标题
      const title = document.createElement('h2');
      // 假设数据中有name字段，如果没有则使用ID作为标题
      title.textContent = data.name || `数据ID: ${data.id}`;
      
      // 创建详情内容
      const detailContent = document.createElement('div');
      
      // 遍历数据对象的所有属性
      Object.entries(data).forEach(([key, value]) => {
          const detailItem = document.createElement('div');
          detailItem.className = 'detail-item';
          
          const label = document.createElement('span');
          label.className = 'detail-label';
          label.textContent = `${key}:`;
          
          const valueSpan = document.createElement('span');
          valueSpan.textContent = value;
          
          detailItem.appendChild(label);
          detailItem.appendChild(valueSpan);
          detailContent.appendChild(detailItem);
      });
      
      // 清空并添加新内容
      detailContainer.innerHTML = '';
      detailContainer.appendChild(title);
      detailContainer.appendChild(detailContent);
  }
  
  function showLoading() {
      loadingElement.style.display = 'block';
      errorElement.style.display = 'none';
      detailContainer.style.display = 'none';
  }
  
  function hideLoading() {
      loadingElement.style.display = 'none';
  }
  
  function showDetailContainer() {
      detailContainer.style.display = 'block';
  }
  
  function showError(message) {
      errorElement.textContent = message;
      errorElement.style.display = 'block';
  }
});
